package org.ciallo.simplemusicplayer.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import com.google.android.material.card.MaterialCardView;
import org.ciallo.simplemusicplayer.R;
import org.ciallo.simplemusicplayer.activity.*;
import org.ciallo.simplemusicplayer.util.ThemeUtil;

/**
 * @author Jukomu
 * @Description: 我的"界面的Fragment，显示用户信息和功能入口
 * @Package: org.ciallo.simplemusicplayer.fragment
 * @Project: SimpleMusicPlayer
 * @name: ProfileFragment
 * @Date: 2025/5/28-02:07
 * @Filename: ProfileFragment
 */
public class ProfileFragment extends Fragment {

    private MaterialCardView cardUserInfo;
    private ImageButton btnLoginEdit;
    private TextView tvUsername, tvUserEmail;
    private TextView tvRecentPlay, tvPlaylistManagement, tvPlayStats;
    private TextView tvSettings, tvAbout;

    // private SharedViewModel sharedViewModel;
    // private UserViewModel userViewModel; // 如果有用户系统

    public ProfileFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_profile, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 初始化ViewModel
        // sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
        // userViewModel = new ViewModelProvider(this).get(UserViewModel.class);

        // 初始化UI控件
        cardUserInfo = view.findViewById(R.id.card_profile_user_info);
        btnLoginEdit = view.findViewById(R.id.button_profile_login_edit);
        tvUsername = view.findViewById(R.id.textView_profile_username);
        tvUserEmail = view.findViewById(R.id.textView_profile_user_email);

        tvRecentPlay = view.findViewById(R.id.textView_profile_recent_play);
        tvPlaylistManagement = view.findViewById(R.id.textView_profile_playlist_management);
        tvPlayStats = view.findViewById(R.id.textView_profile_play_stats);

        tvSettings = view.findViewById(R.id.textView_profile_settings);
        tvAbout = view.findViewById(R.id.textView_profile_about);

        setupClickListeners();
        loadUserInfo(); // 加载用户信息（当前为占位）
    }

    /**
     * 设置各个功能项的点击监听器。
     */
    private void setupClickListeners() {
        // 用户信息区域的点击（例如跳转到登录或编辑资料）
        cardUserInfo.setOnClickListener(v -> handleUserInfoClick());
        btnLoginEdit.setOnClickListener(v -> handleUserInfoClick());

        tvRecentPlay.setOnClickListener(v -> {
            if (getActivity() != null) {
                startActivity(new Intent(getActivity(), RecentPlayActivity.class));
            }
        });

        tvPlaylistManagement.setOnClickListener(v -> {
            if (getActivity() != null) {
                startActivity(new Intent(getActivity(), PlaylistManagementActivity.class));
            }
        });

        tvPlayStats.setOnClickListener(v -> {
            if (getActivity() != null) {
                startActivity(new Intent(getActivity(), PlayStatsActivity.class));
            }
        });

        tvSettings.setOnClickListener(v -> {
            if (getActivity() != null) {
                startActivity(new Intent(getActivity(), SettingsActivity.class)); // 使用 AndroidX Preference
            }
        });

        tvAbout.setOnClickListener(v -> {
            if (getActivity() != null) {
                startActivity(new Intent(getActivity(), AboutActivity.class)); // 启动 AboutActivity
            }
        });
    }

    /**
     * 处理用户信息区域的点击事件 (例如登录/注册或编辑资料)。
     */
    private void handleUserInfoClick() {
        // TODO: 实现登录/注册逻辑或跳转到用户资料编辑页面
        Toast.makeText(getContext(), "登录/编辑资料功能待实现", Toast.LENGTH_SHORT).show();
    }

    /**
     * 加载并显示用户信息 (当前为占位)。
     */
    private void loadUserInfo() {
        // TODO: 如果有用户系统，从UserViewModel或SharedPreferences加载用户信息
        // tvUsername.setText("已登录用户名");
        // tvUserEmail.setText("user@example.com");
    }

    /**
     * 显示主题选择对话框。
     * 这部分逻辑与你之前在 MainActivity 或其他地方实现的主题切换可以复用。
     */
    private void showThemeChooserDialog() {
        if (getContext() == null) return;
        final String[] themes = {"跟随系统", "浅色模式", "深色模式"};
        // 你需要一个方法来获取当前保存的主题设置，例如从 SharedPreferences
        int currentThemeMode = ThemeUtil.getCurrentNightMode(requireContext()); // 假设有 ThemeUtil

        int checkedItem;
        if (currentThemeMode == androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) {
            checkedItem = 0;
        } else if (currentThemeMode == androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_NO) {
            checkedItem = 1;
        } else {
            checkedItem = 2;
        }

        new AlertDialog.Builder(requireContext())
                .setTitle("选择主题")
                .setSingleChoiceItems(themes, checkedItem, (dialog, which) -> {
                    int selectedMode;
                    switch (which) {
                        case 0:
                            selectedMode = androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM;
                            break;
                        case 1:
                            selectedMode = androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_NO;
                            break;
                        case 2:
                            selectedMode = androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_YES;
                            break;
                        default:
                            return;
                    }
                    ThemeUtil.applyAndSaveNightMode(requireContext(), selectedMode); // 假设有 ThemeUtil
                    dialog.dismiss();
                })
                .setNegativeButton(R.string.cancel, null)
                .show();
    }
}